<?php


namespace app\api\controller;



use app\common\model\SmokeCostRecord;
use app\common\model\SmokeRecord;

use app\api\controller\AuthBase;

use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use function Composer\Autoload\includeFile;

class Mine extends AuthBase
{
    public function info(){
        $user=Db::name('user')
            ->where('id',$this->userId)
            ->field('id,nickname,age_time,phone,email,is_vip,vip_end_time,unionid')
            ->find();
        //计算烟龄
        $age=get_smoke_age($user['age_time']);
        $user['age_time']=$user['age_time']?date("Y-m-d",$user['age_time']):'';
        $user['vip_end_time']=date("Y-m-d",$user['vip_end_time']);
        $user['age']=$age;
        $user['is_vip']=$this->is_vip;
        //
        return $this->show(1,'success',$user);
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 修改个人信息
     */
    public function edit_info(){
        $data=input('post.');
        try {
            validate(\app\common\validate\Mine::class)
                ->scene("edit_info")
                ->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->show(0, $e->getError());
        }
        $res=Db::name('user')->where('id',$this->userId)->update(
            ['nickname'=>$data['nickname'],'age_time'=>strtotime($data['age_time']),'email'=>$data['email']]
        );
        if ($res){
            return $this->show(1,'保存成功');
        }
        return show(0,'保存失败');
    }
    /**
     * 分析报告
     */
    public function reports(){
        $type=input('get.type');
        $smoke=SmokeRecord::where('user_id',$this->userId);
        $cost=SmokeCostRecord::where('user_id',$this->userId);
        switch ($type){
            case 1:
                $smoke=$smoke->whereMonth('smoke_date');
                $cost=$cost->whereMonth('buy_date');
                $num=get_month();
                break;
            case 2:
                $smoke=$smoke->whereMonth('smoke_date','last month');
                $cost=$cost->whereMonth('buy_date','last month');
                $num=get_last_month();
                break;
        }
        $smoke=$smoke->field([
            'SUM(tar) as tar_sum',
            'SUM(nicotine) as nicotine_sum',
            'SUM(co) as co_sum',
            'SUM(num) as num_sum'
        ])
            ->find()->toArray();
        $cost=$cost->sum('price');
        $avg_smoke=round($smoke['num_sum']/$num,2);
        $avg_cost=round($cost/$num,2);
        $level=get_level($avg_smoke);
        $result['level']=$level;
        $result['avg_smoke']=$avg_smoke;
        $result['avg_cost']=$avg_cost;
        $result['smoke_num']=$smoke['num_sum'];
        $result['cost']=$cost;
        $result['nicotine']=$smoke['nicotine_sum'];
        $result['tar']=$smoke['tar_sum'];
        $result['co']=$smoke['co_sum'];
        return show(1,'',$result);
    }
    public function report(){

        // 获取上周一的日期
        $lastMonday = date('m月d日', strtotime('last week'));
// 获取上周日的日期
        $lastSunday = date('m月d日', strtotime('last Sunday'));

        $smoke=SmokeRecord::where('user_id',$this->userId)->whereTime('smoke_date', 'last week');
        $cost=SmokeCostRecord::where('user_id',$this->userId)->whereTime('buy_date', 'last week');;

        $smoke=$smoke->field([
            'SUM(tar) as tar_sum',
            'SUM(nicotine) as nicotine_sum',
            'SUM(co) as co_sum',
            'SUM(num) as num_sum'
        ])
            ->find()->toArray();
        $cost=$cost->sum('price');
        $avg_smoke=round($smoke['num_sum']/7,2);
        $level=get_level($avg_smoke);
        $injurant=round($smoke['nicotine_sum']+$smoke['tar_sum']+$smoke['co_sum'],2);
        //上上周的数据
        $twoWeeksAgoMonday = strtotime('2 weeks ago last Monday');
// 获取上上周日的时间戳
        $twoWeeksAgoSunday = strtotime('2 weeks ago last Sunday')+86399;
        $smokes=SmokeRecord::where('user_id',$this->userId)->where(['smoke_date'=>[$twoWeeksAgoMonday,$twoWeeksAgoSunday]]);
        $costs=SmokeCostRecord::where('user_id',$this->userId)->where(['buy_date'=>[$twoWeeksAgoMonday,$twoWeeksAgoSunday]]);

        $smokes=$smokes->field([
            'SUM(tar) as tar_sum',
            'SUM(nicotine) as nicotine_sum',
            'SUM(co) as co_sum',
            'SUM(num) as num_sum'
        ])
            ->find()->toArray();
        $costs=$costs->sum('price');
        $injurants=$smokes['nicotine_sum']+$smokes['tar_sum']+$smokes['co_sum'];
        //判断有几项增长有几项下降
        $result['week_time']="数据范围:".$lastMonday."-".$lastSunday;
        $result['level']=$level;
        $result['nickname']=Db::name('user')->where('id',$this->userId)->value('nickname');
        $result['smoke_num']=$smoke['num_sum'];
        $result['cost']=$cost;
        $result['injurant']=$injurant;
        $result['smoke_num_arrows']=get_shangsheng_xiajiang($smoke['num_sum'],$smokes['num_sum']);
        $result['cost_arrows']=get_shangsheng_xiajiang($cost,$costs);
        $result['injurant_arrows']=get_shangsheng_xiajiang($injurant,$injurants);
        $result['wenan']=get_report_wenan([$result['smoke_num_arrows'],$result['cost_arrows'],$result['injurant_arrows']]);
        $dates = [];
// 循环获取近 12 个日期
        $lastSunday = date('Y-m-d', strtotime('last Sunday'));
        for ($i = 0; $i < 7; $i++) {
            // 计算当前循环对应的日期
            $date = date('Y-m-d', strtotime("-$i days", strtotime($lastSunday)));
            $dates[] = $date;
        }
        $results=[];
        $min=0;
        $min_date=0;
        foreach ($dates as $k=>$v){
            $one=explode('-',$v);
            $results[$k]['date']=end($one);
            $num=Db::name('smoke_record')
                ->where(['user_id'=>$this->userId])
                ->whereDay('smoke_date',$v)
                ->sum('num');
            $results[$k]['num']=$num;
            if ($num>$min){
                $min=$num;
                $min_date=$v;
            }
        }
        $result['smoke_arr']=array_reverse($results);
        if (!$result['smoke_num']){
            $result['dibu']['num']=0;
            $result['smoke_num']=0;
        }else{
            $result['dibu']['date']=date("m年d日",strtotime($min_date));
            $result['dibu']['num']=$min;
            //找到那天
        }
        $dibu=smokeRecord::where('user_id',$this->userId)
            ->whereDay('smoke_date',$min_date)
            ->field([
            'SUM(tar) as tar_sum',
            'SUM(nicotine) as nicotine_sum',
            'SUM(co) as co_sum'
        ])
            ->find()->toArray();
        $result['dibu']['injurant']=round($dibu['nicotine_sum']+$dibu['tar_sum']+$dibu['co_sum'],2);
        return show(1,'',$result);
    }
    /**
     * 关于我们
     */
    public function about_us(){
        $model=Db::name('system')
            ->where('id',1)
            ->find();
        return show(1,'success',$model);
    }
    /**
     * 修改手机号
     */
    public function edit_phone(){
        $phone=input('post.phone');
        $code=input('post.code');
        $code_redis=Cache::get($phone.$code);
        if($code!=$code_redis){
            return show(0,'验证码错误');
        }
        $user=Db::name('user')->where('phone',$phone)->find();
        if ($user){
            return show(0,'当前手机号已存在');
        }
        $res=Db::name('user')->where('id',$this->userId)->update(['phone'=>$phone]);
        if (!$res){
            return show(0,'保存失败');
        }
        return show(1,'保存成功');
    }
    /**
     * 修改手机号
     */
    public function edit_email(){
        $phone=input('post.email');
        $code=input('post.code');
        $code_redis=Cache::get($phone.$code);
        if($code!=$code_redis){
            return show(0,'验证码错误');
        }
        $user=Db::name('user')->where('email',$phone)->find();
        if ($user){
            return show(0,'当前邮箱已存在');
        }
        $res=Db::name('user')->where('id',$this->userId)->update(['email'=>$phone]);
        if (!$res){
            return show(0,'保存失败');
        }
        return show(1,'保存成功');
    }
    /**
     * 会员中心
     */
    public function vip(){
        $user=Db::name('user')
            ->where('id',$this->userId)
            ->field('id,nickname,is_vip,vip_end_time')
            ->find();
        if ($user['vip_end_time']<time()){
            $user['vip_end_time']="已到期";
        }else{
            $user['vip_end_time']=date("Y-m-d",$user['vip_end_time']);
        }
        $goods=Db::name('vip_goods')
            ->order('sort desc')
            ->column('id,name,price,brief,product_id,apple_id');
        $data['user']=$user;
        $data['goods']=$goods;
        return show(1,'success',$data);
    }
    /**
     * 活动页面
     */
    public function activity(){
        $activity_rule[]="邀请新用户填写您的邀请码完成注册";
        $activity_rule[]="邀请一个新用户赠送7天vip";
        $activity_rule[]="非年费会员用户,邀请10个新用户赠送价值12元普通奖品";
        $activity_rule[]="年费会员用户,邀请15个新用户赠送价值58元vip奖品";
        $activity_rule[]="永久会员用户,邀请20个新用户赠送价值88元超级奖品";
        $activity_rule[]="新疆西藏地区不包邮,无任何套路,不收取任何费用";
        $xiaohongshu[]="小红书发帖宣传火因记";
        $xiaohongshu[]="帖子在48h内浏览量>100,赠送1个月vip";
        $xiaohongshu[]="帖子浏览量>1000,赠送6个月vip";
        $xiaohongshu[]="帖子浏览量>10000,赠送12个月vip";
        $wechat_rule[]="朋友圈宣传火因记";
        $wechat_rule[]="点赞量>10,赠送1个月vip";
        $wechat_rule[]="点赞量>50,赠送6个月vip";
        $wechat_rule[]="点赞量>100,赠送12个月vip";
        //邀请记录
        $invite_record=Db::name('invite_record')
            ->where('i.pid',$this->userId)
            ->alias('i')
            ->leftJoin('user u','i.uid=u.id')
            ->column('u.phone,u.create_time');
        foreach ($invite_record as $k=>$v){
            $invite_record[$k]['date']=date("Y-m-d",$v['create_time']);
            $invite_record[$k]['time']=date("H:i:s",$v['create_time']);
            $invite_record[$k]['phone']=get_hide_phone($v['phone']);
        }
        $user=Db::name('user')
            ->where('id',$this->userId)
            ->find();
        $system=Db::name('system')
            ->where('id',1)
            ->find();
        $data['invite_code']=$user['invite_code'];
        $data['activity_rule']=$activity_rule;
        $data['invite_record']=$invite_record;
        $data['putong']="http://img.smokeji.com/IMG_8118.JPG";
        $data['vip']="http://img.smokeji.com/IMG_8119.jpg";
        $data['svip']="http://img.smokeji.com/IMG_8192.jpg";
        $data['xiaohongshu']=$xiaohongshu;
        $data['wechat_rule']=$wechat_rule;
        $data['wechat']=$system['wechat'];
        $data['wechat_img']=$system['wechat_img'];
        return show(1,'',$data);
    }
    /**
     * 目标页面
     */
    public function target(){
        $model=Db::name('user_target')
            ->where('user_id',$this->userId)
            ->find();
        if (!$model){
            return show(10);
        }

        if ($model['cycle_end']<time()){
            $data['status']=2;
        }
        if ($model['cycle_begin']<time()&&$model['cycle_end']>time()){
            $data['status']=1;
        }
        if ($model['cycle_begin']>time()){
            $data['status']=3;
        }
        $data['cycle_begin']=date("Y-m-d",$model['cycle_begin']);
        $data['cycle_end']=date("Y-m-d",$model['cycle_end']);
        $data['num']=$model['num'];
        $data['award']=$model['award'];
        //计算当前烟瘾
        $smoke=SmokeRecord::where('user_id',$this->userId)
            ->where('smoke_date','between',[$model['cycle_begin'],time()])
            ->sum('num');
        $day=get_diff_day($model['cycle_begin'],time());
        $avg_smoke=round($smoke/$day,2);
        $target_day=get_diff_day($model['cycle_end'],$model['cycle_begin']);
        if ($data['status']==1){
            $wenan="进行中";
        }else if($data['status']==2){
            if ($avg_smoke<=$data['num']){
                $wenan="目标达成,即时奖励自己吧";
            }else{
                $wenan="未完成目标,再接再厉吧";
            }
        }else{
            $wenan="还未开始";
        }
        $data['avg_smoke']=$avg_smoke;
        $data['wenan']=$wenan;
        return show(1,'success',$data);
    }
    /**
     * 增加目标
     */
    public function add_target(){
        $data=input('post.');

        $result['cycle_begin']=strtotime($data['cycle_begin']." 00:00:00");

        $result['cycle_end']=strtotime($data['cycle_end']." 23:59:59");
        if ($result['cycle_end']<time()){
            return show(0,'结束时间不能小于今天');
        }
        if ($result['cycle_begin']<time()){
            return show(0,'开始时间不能小于今天');
        }
        if ($result['cycle_end']<$result['cycle_begin']){
            return show(0,'结束时间不能小于开始时间');
        }
        if (!$data['award']){
            return show(0,'请填写奖励');
        }
        $result['num']=$data['num'];
        $result['award']=$data['award'];
        $result['update_time']=time();
        $result['user_id']=$this->userId;
        $one=Db::name('user_target')
            ->where('user_id',$this->userId)
            ->find();
        if ($one){
            $res=Db::name('user_target')
                ->where('id',$one['id'])
                ->update($result);
        }else{
            $result['create_time']=time();
            $res=Db::name('user_target')
                ->insert($result);
        }
        if (!$res){
            return show(0,'保存失败');
        }
        return show(1,'保存成功');
    }
    //添加历史数据
    public function add_history(){
        $data=input('post.');
        if ($data['age']<1){
            return $this->show(0,'烟龄不能小于一年');
        }
        if (!$data['avg_smoke']){
            return $this->show(0,'请填写每天吸入');
        }
        if (!$data['smoke_id_one']){
            return $this->show(0,'请填写常抽的烟1');
        }
        $id_arr=[];
        $id_arr[]=$data['smoke_id_one'];
        $id_arr[]=!empty($data['smoke_id_two'])?$data['smoke_id_two']:0;
        $id_arr[]=!empty($data['smoke_id_three'])?$data['smoke_id_three']:0;
        $id_arr=array_filter($id_arr);
        $smoke=Db::name('smoke')
            ->where(['id'=>$id_arr])
            ->field([
                'SUM(price) as price_sum',
                'SUM(tar) as tar_sum',
                'SUM(nicotine) as nicotine_sum',
                'SUM(co) as co_sum'
            ])
            ->find();
        //算出平均价格
        $count=count($id_arr);
        $avg_price=$smoke['price_sum']/$count;
        $avg_tar=$smoke['tar_sum']/$count;
        $avg_nicotine=$smoke['nicotine_sum']/$count;
        $avg_co=$smoke['co_sum']/$count;

        $sum_smoke=$data['age']*365*$data['avg_smoke'];
        $sum_price=$sum_smoke/20*$avg_price;
        $level=get_level_name($data['avg_smoke']);
        $yanyin=$level['name'];
        $jieyanwenan=$level['wenan'];
        //焦油
        $tar=round($sum_smoke*$avg_tar*0.2,2);
        $nicotine=round($sum_smoke*$avg_nicotine*0.3,2);
        $co=round($sum_smoke*$avg_co*0.6,2);
        if($data['avg_smoke']>10){
            $wenan2="您的烟瘾程度较高,建议您控制吸烟";
        }else{
            $wenan2="您的烟瘾程度较低,建议您尽早戒烟";
        }
        $result['age']=$data['age'];
        $result['avg_smoke']=$data['avg_smoke'];
        $result['smoke_id_one']=$data['smoke_id_one'];
        $result['smoke_id_two']=!empty($data['smoke_id_two'])?$data['smoke_id_two']:0;
        $result['smoke_id_three']=!empty($data['smoke_id_three'])?$data['smoke_id_three']:0;
        $result['sum_smoke']=$sum_smoke;
        $result['sum_price']=$sum_price;
        $result['yanyin']=$yanyin;
        $result['jieyanwenan']=$jieyanwenan;
        $result['tar']=$tar;
        $result['tar_wenan']=round($tar/100,2);
        $result['nicotine']=$nicotine;
        $result['nicotine_wenan']=floor($nicotine/0.9/1000);
        $result['co']=$co;
        $result['wenan2']=$wenan2;
        $history=Db::name('user_smoke_history')
            ->where('user_id',$this->userId)
            ->find();
        if ($history){
            $result['update_time']=time();
            $res=Db::name('user_smoke_history')
                ->where(['id'=>$history['id'],'user_id'=>$this->userId])
                ->update($result);
        }else{
            $result['user_id']=$this->userId;
            $result['create_time']=time();
            $result['update_time']=time();
            $res=Db::name('user_smoke_history')
                ->insert($result);
        }
        if (!$res){
            return $this->show(0,'保存失败');
        }
        return show(1,'保存成功');
    }
    //抽烟历史
    public function smoke_history(){
        $model=Db::name('user_smoke_history')
            ->where('user_id',$this->userId)
            ->find();
        if (!$model){
            return show(10);
        }
        $model["smoke_id_one_name"]=Db::name('smoke')
            ->where('id',$model['smoke_id_one'])
            ->value('name');
        $model["smoke_id_two_name"]=Db::name('smoke')
            ->where('id',$model['smoke_id_two'])
            ->value('name');
        $model["smoke_id_three_name"]=Db::name('smoke')
            ->where('id',$model['smoke_id_three'])
            ->value('name');
        if (!$model){
            return show(2,'请先填写历史数据');
        }
        return show(1,'success',$model);
    }
    /**
     * 退出登录
     */
    public function logout(){
        $token=input('get.token');
        Cache::delete($token);
        return show(1,'退出登录成功');
    }
    /**
     * 绑定微信
     */
    public function bind_wechat(){
        $accessToken = input('access_token');
        $openId = input('openid');

        // 获取用户信息
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openId}&lang=zh_CN";
        $userInfoResponse = curl_get($userInfoUrl);
        $userInfo = json_decode($userInfoResponse, true);
        if (isset($userInfo['errcode'])) {
            return show(0,'获取失败');
        }
        $res=Db::name('user')
            ->where(['openid'=>$userInfo['openid'],'unionid'=>$userInfo['unionid']])
            ->count();
        if ($res){
            return show(0,'此微信号已被绑定过');
        }
        $ress=Db::name('user')
            ->where('id',$this->userId)
            ->update(['openid'=>$userInfo['openid'],'unionid'=>$userInfo['unionid']]);
        if (!$ress){
            return show(0,'绑定失败');
        }
        return show(1,'绑定成功');
    }
    /**
     * 绑定手机号
     */
    public function xcx_bind_phone(){
        $token =$this->getAccessToken();
        $code = input('code');
        $wxLoginUrl = sprintf(config('wxxcx.get_phone_url'),$token);
        $result = doCurl($wxLoginUrl,1,['code'=>$code]);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            return show(0, '获取手机号报错,微信服务内部报错');
        } else {
            if ($wxResult['errcode'] != 0) {
                return show(0, '登录报错请重试');
            }
        }
        $phone=$wxResult['phone_info']['purePhoneNumber'];
        $user=Db::name('user')
            ->where('phone',$phone)
            ->find();
        if ($user){
            return show(0,'此手机号已注册账号');
        }
        $res=Db::name('user')
            ->where('id',$this->userId)
            ->update(['phone'=>$phone]);
        if ($res){
            return show(1,'绑定成功');
        }
        return show(0,'绑定失败');
    }
}
